const CFG = require('./config');
const FUN = require('./comm/func');
const mqttConn = require('./utils/mqttConn');
const mqttSrv = require('./utils/mqttSrv'); // 在当前ip下新建mqtt服务器

if (FUN.isLocal()) {
  console.log("\n\nIs Local Host:", require("os").hostname());
} else {
  console.log("\n\nIs Remote Srv:", require("os").hostname());
}

const shareEvt = require('events').EventEmitter;
global.shareEvt = new shareEvt(); // 定义公共事件主体
global.shareEvt.on('mqtt_srv_ready', ()=>{
  mqttConn.newClient('admin.7'+FUN.rand(12345678,99999999), mqSrvManagerCb);
})

// 连接回调
function mqSrvManagerCb(conn)
{
  let MqHandler = {};
  let Topics = [];

  //订阅主题
  Topics.push('srv/notify');
  Topics.push('srv/debug');
  console.log('[Sub Topic]', Topics.join(', '));

  conn.msgHdrs = [];
  conn.msgHdrs.push(MqHandler); // 注册回调app
  MqHandler.mqConn = conn;
  MqHandler.mqPub = function (topic, payload, opts={retain:false}) {//mqtt发包函数
    if (FUN.isLocal()) { console.log('N>>',topic,payload);return; }//防止本地调试时，对在线设备重复发包
    conn.publish(topic, payload, opts);
    if (!opts.nolog) console.log('>>>', topic, payload);
  }
  MqHandler.mqMsgIn = function(Path, Payload, Packet) { // 收包回调
    if (Path.func == 'debug' && Payload.toString() == 'mqsrv') {
      mqttSrv.DebugActList();
    } else if (Path.func == 'notify' && Payload.toString() == 'mqsrv_clean_dev_list') {
      mqttSrv.ClearActList('dev'); // 在srv/notify主题收到mqsrv_clean_list就必须刷新缓存，设备表用户表改动都必须刷
    } else if (Path.func == 'notify' && Payload.toString() == 'mqsrv_clean_user_list') {
      mqttSrv.ClearActList('user'); // 在srv/notify主题收到mqsrv_clean_list就必须刷新缓存，设备表用户表改动都必须刷
    }
  }
  conn.subscribe(Topics, (err)=>{ if(err)console.log('err2:',err) });
}